package com.code2roc.jarmanage.util;

import com.code2roc.jarmanage.depoly.DepolyPlatform;
import oshi.SystemInfo;
import oshi.software.os.OSProcess;
import oshi.software.os.OperatingSystem;
import oshi.software.os.windows.WindowsOperatingSystem;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.lang.management.ManagementFactory;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


public class ProcessUtil {

    public static int getProcessID(String processName) {
        int pid = -1;
        if (EnviromentUtil.getDepolyPlaform().equals(DepolyPlatform.Windows)) {
            try {
                ProcessBuilder pb = new ProcessBuilder("tasklist", "/fo", "csv", "/nh");
                Process process = pb.start();
                BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
                String line;
                while ((line = reader.readLine()) != null) {
                    if (line.toLowerCase().contains(processName.toLowerCase())) {
                        String[] parts = line.split(",");
                        pid = Integer.parseInt(parts[1].replace("\"", ""));
                        break;
                    }
                }
            } catch (Exception e) {
                LogUtil.error(e);
            }
        } else {
            try {
                ProcessBuilder pb = new ProcessBuilder("ps", "-e", "-o", "pid,args");
                Process process = pb.start();
                BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
                String line;
                while ((line = reader.readLine()) != null) {
                    if (line.contains(processName)) {
                        String[] parts = line.trim().split("\\s+");
                        pid = Integer.parseInt(parts[0]);
                        break;
                    }
                }
            } catch (Exception e) {
                LogUtil.error(e);
            }
        }
        return pid;
    }
}
